package com.carlinfo.controller.back_redirect;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.common.util.EncryptUtil;
import com.carlinfo.common.util.PageInfoUtil;
import com.carlinfo.users.pojo.AAdmin;
import com.carlinfo.users.pojo.ACourse;
import com.carlinfo.users.pojo.ANews;
import com.carlinfo.users.pojo.APartner;
import com.carlinfo.users.pojo.AQqInfo;
import com.carlinfo.users.pojo.ATeachers;
import com.carlinfo.users.service.IAdminService;
import com.carlinfo.users.service.ICourseService;
import com.carlinfo.users.service.INewsService;
import com.carlinfo.users.service.IPartnerService;
import com.carlinfo.users.service.IQqInfoService;
import com.carlinfo.users.service.ITeachersService;

/**
 * 
 * @author Gonsen
 * 后台管理页面
 */
@Controller
@RequestMapping("/back")
public class AdminHeadRedirectController {

	@Resource
	private INewsService newsService;
	@Resource
	private IPartnerService partnerService;
	@Resource
	private ICourseService courseService;
	@Resource
	private ITeachersService teachersService;
	@Resource
	private IAdminService adminService;
	@Resource
	private IQqInfoService qqInfoService;

	/**
	 * 登录后首页
	 * @return /back/index
	 */
	@RequestMapping("/index")
	public String index() {
		return "/back/index";
	}

	/**
	 * 登陆后欢迎页面
	 * @return /back/welcome
	 */
	@RequestMapping("/welcome")
	public String welcome() {
		return "/back/welcome";
	}

	/**
	 * 新闻操作页面
	 * @param pageSize
	 * @param currentPage
	 * @param model
	 * @return /back/article-list
	 */
	@RequestMapping("/article-list")
	public String news(String pageSize, String currentPage, Model model) {
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		if (currentPage == null) {
			currentPage = "1";
		}
		if (pageSize != null) {
			pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
		}
		pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));

		List<ANews> newsList = newsService.findCondNewsList(pageInfoUtil, new HashMap<>());
		model.addAttribute("newsList", newsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		return "/back/article-list";
	}

	/**
	 * 新闻添加页面
	 * @param type
	 * @param id
	 * @param model
	 * @return /back/article-add
	 */
	@RequestMapping("/article-add")
	public String add(String type, String id, Model model) {
		if (type == null || type.equals("add")) {

		} else if (type.equals("edit")) {
			Map<String, Object> conMap = new HashMap<>();
			conMap.put("id", id);
			ANews news = newsService.findOneNewsService(conMap);
			model.addAttribute("news", news);

		}
		return "/back/article-add";
	}

	@RequestMapping("news_{type}")
	public String news(HttpServletRequest request , @PathVariable String type, ANews news, MultipartFile img) {
		System.out.println(type);

		if (img != null && !img.isEmpty()) {
			System.out.println(img.getOriginalFilename());
			String realPath = request.getServletContext().getRealPath("/");
			System.out.println(realPath);
			String path = "/img/data/" + new Date().getTime() + "-" + img.getOriginalFilename();
			File f = new File(realPath + path);
			try {
				img.transferTo(f);
				news.setImgPath(path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(news);
		news.setUpdateTime(new Date());
		news.setPubTime(new Date());
		if (type == null || type.equals("add")) {
			news.setCreateTime(new Date());
			newsService.saveOneService(news);
		} else if (type.equals("edit")) {
			newsService.updateOneService(news);
		} else if (type.equals("delete")) {
			System.out.println("====================delete====================");
			Map<String, Object> condMap = new HashMap<>();
			condMap.put("id", news.getId());
			newsService.deleteOneService(condMap);
		}
		return "redirect:/back/article-list.htm";
	}

	@RequestMapping("/product-{type}")
	public String product(@PathVariable String type, String currentPage, String pageSize, Model model) {
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		if (currentPage == null) {
			currentPage = "1";
		}
		if (pageSize != null) {
			pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
		}
		pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("orderby", "desc");
		if (type.equals("partner")) {
			List<APartner> partners = partnerService.findCondPartnerList(pageInfoUtil, condMap);
			model.addAttribute("partners", partners);
		} else if (type.equals("course")) {
			List<ACourse> courses = courseService.findCondProdList(pageInfoUtil, condMap);
			model.addAttribute("courses", courses);
		} else if (type.equals("teacher")) {
			List<ATeachers> teachers = teachersService.findCondTeachersList(pageInfoUtil, condMap);
			model.addAttribute("teachers", teachers);
		}
		model.addAttribute("pageInfoUtil", pageInfoUtil);
		return "/back/product-" + type;
	}

	@RequestMapping("/codeing")
	public String codeing(String id, Model model) {
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("id", id);
		APartner partner = partnerService.findOnePartnerSercice(condMap);
		model.addAttribute("partner", partner);
		return "/back/codeing";
	}
		
	@RequestMapping("/partner_{type}")
	public String partner(HttpServletRequest request , @PathVariable String type, MultipartFile logo, APartner partner, Model model) {
		System.out.println(type);
		System.out.println(logo);
		System.out.println(partner);
		try {
			JSONObject jsonObject = null;
			Map<String, Object> condMap = new HashMap<>();
			if (type.equals("add")) {
				/*String realPath = request.getServletContext().getRealPath("/");
				String path = "/img/logo/" + new Date().getTime() + "-" + logo.getOriginalFilename();
				File file = new File(realPath + path);*/
				String realPath = request.getServletContext().getRealPath("/");
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
				String datePath = sdf.format(date);
				String path = "/img/" + datePath ;
				File file = new File(realPath + path);
				if (!file.exists()) {
					file.mkdirs();
					}
					String db_filePath = path + new Date().getTime() + ".jpg";
					String filePath = realPath + db_filePath;
					File file_copy = new File(filePath);
					logo.transferTo(file_copy);
					partner.setPartnerLogo(db_filePath);
					

				jsonObject = partnerService.saveOneService(partner);
			} else if (type.equals("delete")) {
				condMap.put("id", partner.getId());
				jsonObject = partnerService.deleteOneService(condMap);
			} else if (type.equals("update")) {
				System.out.println("=========" + partner);
				System.out.println("logo" + logo);
				if (logo != null && !logo.isEmpty()) {
					String realPath = request.getServletContext().getRealPath("/");
					Date date = new Date();
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
					String datePath = sdf.format(date);
					String path = "/img/" + datePath ;
					File file = new File(realPath + path);
					if (!file.exists()) {
						file.mkdirs();
						}
						String db_filePath = path + new Date().getTime() + ".jpg";
						String filePath = realPath + db_filePath;
						File file_copy = new File(filePath);
						logo.transferTo(file_copy);
						partner.setPartnerLogo(db_filePath);
				}
				jsonObject = partnerService.updateOneService(partner);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println("========================jieshu====================");
		return "redirect:/back/product-partner.htm";
	}

	@RequestMapping("/course")
	public String courseOpt(String type, String id, Model model) {
		if (type != null && type.equals("add")) {

		} else if (type != null && type.equals("edit") & id != null && !id.isEmpty()) {
			Map<String, Object> condMap = new HashMap<>();
			condMap.put("id", Integer.valueOf(id));
			ACourse course = courseService.findOneProdService(condMap);
			model.addAttribute("course", course);
		}
		return "/back/course-add";
	}

	@RequestMapping("/course_{type}")
	public String course(HttpServletRequest request , @PathVariable String type, MultipartFile courseImage, ACourse course, Model model) {
		try {
			System.out.println(course);
			if (courseImage != null && !courseImage.isEmpty()) {
				String realPath = request.getServletContext().getRealPath("/");
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
				String datePath = sdf.format(date);
				String path = "/img/" + datePath ;
				File file = new File(realPath + path);
				if (!file.exists()) {
					file.mkdirs();
					}
					String db_filePath = path + new Date().getTime() + ".jpg";
					String filePath = realPath + db_filePath;
					File file_copy = new File(filePath);
					courseImage.transferTo(file_copy);
					course.setCourseImg(db_filePath);
			}
			Map<String, Object> condMap = new HashMap<>();
			if (type.equals("add")) {
				courseService.saveOneService(course);
			} else if (type.equals("delete")) {
				condMap.put("id", course.getId());
				courseService.deleteOneService(condMap);
			} else if (type.equals("edit")) {
				courseService.updateOneService(course);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "redirect:/back/product-course.htm";
	}
	
	@RequestMapping("/teacher")
	public String teacherOpt(String type, String id, Model model) {
		if (type != null && type.equals("add")) {

		} else if (type != null && type.equals("edit") & id != null && !id.isEmpty()) {
			System.out.println("=======================\n"
					+ "=========================\n"
					+ "=========================\n");
			
			Map<String, Object> condMap = new HashMap<>();
			condMap.put("id", Integer.valueOf(id));
			ATeachers teacher = teachersService.findOneTeachersService(condMap);
			model.addAttribute("teacher", teacher);
		}
		return "/back/teacher-add";
	}
	
	@RequestMapping("/teacher_{type}")
	public String teacher(HttpServletRequest request , @PathVariable String type, MultipartFile teacherImg, ATeachers teacher, Model model) {
		try {
			System.out.println(teacher);
			if (teacherImg != null && !teacherImg.isEmpty()) {
				String realPath = request.getServletContext().getRealPath("/");
				Date date = new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
				String datePath = sdf.format(date);
				String path = "/img/" + datePath ;
				File file = new File(realPath + path);
				if (!file.exists()) {
					file.mkdirs();
					}
				String db_filePath = path + new Date().getTime() + ".jpg";
				String filePath = realPath + db_filePath;
				File file_copy = new File(filePath);
				teacherImg.transferTo(file_copy);
				teacher.setPhotoPath(db_filePath);
			}
			Map<String, Object> condMap = new HashMap<>();
			if (type.equals("add")) {
				teachersService.saveOneService(teacher);
			} else if (type.equals("delete")) {
				condMap.put("id", teacher.getId());
				teachersService.deleteOneService(condMap);
			} else if (type.equals("edit")) {
				teachersService.updateOneService(teacher);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "redirect:/back/product-teacher.htm";
	}
	
	@RequestMapping("/admin")
	public String adminOpt(String type, String id, Model model) {
		if (type != null && type.equals("add")) {

		} else if (type != null && type.equals("edit") & id != null && !id.isEmpty()) {
			System.out.println("=======================\n"
					+ "=========================\n"
					+ "=========================\n");
			
			Map<String, Object> condMap = new HashMap<>();
			condMap.put("id", Integer.valueOf(id));
			AAdmin admin = adminService.findOneAdminSercice(condMap);
			model.addAttribute("admins", admin);
		}
		return "/back/admin-add";
	}
	
	@RequestMapping("/admin_{type}")
	public String admin(HttpServletRequest request , @PathVariable String type, MultipartFile teacherImg, AAdmin admin, Model model) throws IOException {
		System.out.println(admin);
		Map<String, Object> condMap = new HashMap<>();
		if (type.equals("add")) {
			admin.setCreatetime(new Date());
			admin.setPassword(EncryptUtil.sha256EncodeStr(admin.getPassword()));
			admin.setUpdatetime(new Date());
			adminService.saveOneService(admin);
		} else if (type.equals("delete")) {
			condMap.put("id", admin.getId());
			adminService.deleteOneService(condMap);
		} else if (type.equals("edit")) {
			admin.setUpdatetime(new Date());
			condMap.put("id", admin.getId());
			if(admin.getPassword()!=null&&!admin.getPassword().isEmpty()) {
				admin.setPassword(EncryptUtil.sha256EncodeStr(admin.getPassword()));
			}else {
				AAdmin admin2 = adminService.findOneAdminSercice(condMap);
				admin.setPassword(admin2.getPassword());
			}

			adminService.updateOneService(admin);
		}
		return "redirect:/back/admin-list.htm";
	}
	
	@RequestMapping("/admin-list")
	public String admin_list(Model model) {
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		Map<String, Object> condMap = new HashMap<>();
		List<AAdmin> admins = adminService.findCondAdminList(pageInfoUtil, condMap);
		model.addAttribute("admins", admins);
		return "/back/admin-list";
	}
	
	/**
	 * QQ客服页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/customer-service")
	public String customer_service(Model model) {
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		Map<String, Object> condMap = new HashMap<>();
		List<AQqInfo> qqInfo = qqInfoService.findCondQqInfoList(pageInfoUtil, condMap);
		model.addAttribute("qqInfo", qqInfo);
		return "/back/customer-service";
	}
	
	@RequestMapping("/qqInfo-add")
	public String customer(String type,String id,Model model) {
		if (type != null && type.equals("add")) {

		} else if (type != null && type.equals("edit") & id != null && !id.isEmpty()) {
			System.out.println("=======================\n"
					+ "=========================\n"
					+ "=========================\n");
			
			Map<String, Object> condMap = new HashMap<>();
			condMap.put("id", Integer.valueOf(id));
			AQqInfo qqInfo = qqInfoService.findOneQqInfoService(condMap);
			model.addAttribute("qqInfo", qqInfo);
		}
		return "/back/qqInfo-add";
	}

	@RequestMapping("/qqInfo")
	public String qqInfo(HttpServletRequest request , String type, AQqInfo qqInfo, Model model) {
		System.out.println(qqInfo);
		Map<String, Object> condMap = new HashMap<>();
		if (type.equals("add")) {
			qqInfoService.saveOneService(qqInfo);
		} else if (type.equals("delete")) {
			condMap.put("id", qqInfo.getId());
			qqInfoService.deleteOneService(condMap);
		} else if (type.equals("edit")) {
			qqInfoService.updateOneService(qqInfo);
		}
		return "redirect:/back/customer-service.htm";
	}
	
	@RequestMapping("*")
	public String all(HttpServletRequest request) {
		String path = request.getServletPath().substring(0, request.getServletPath().lastIndexOf("."));
		System.out.println(path);
		return path;
	}

}